package com.zjy.config;

import com.zjy.pojo.User;
import com.zjy.service.impl.UserServiceimpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author Zhengjz
 * @version 1.0
 * @className UserRealm
 * @date 2021/1/10 14:51
 */

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserServiceimpl userServiceimpl;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("-----------》授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //拿到当前登录的用户
        Subject subject = SecurityUtils.getSubject();
        //拿到user对象
        User principal = (User) subject.getPrincipal();
        //设置权限
        info.addStringPermission(principal.getAuthority());
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
     UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        Subject subject = SecurityUtils.getSubject();
        User user = userServiceimpl.getName(token.getUsername());
        if(user == null){
            return null;

        }


        return new SimpleAuthenticationInfo(user,user.getUserPassword(),"");
    }
}
